// npm install jsqr
import jsQR from "jsqr";
import { toDataURL } from "qrcode";

// 模拟 a 标签下载文件
export const downFile = (
  src: string | Blob | File | ArrayBuffer,
  title = "default.png"
) => {
  const url =
    typeof src === "string" ? src : URL.createObjectURL(new Blob([src]));
  const a = document.createElement("a");
  a.style.display = "none";
  a.href = url;
  a.download = title;
  a.click();
  URL.revokeObjectURL(url);
  a.remove();
};

/**
 * 文件转换：File 转 string、blob、buffer
 * @param {File} file
 * @param {String} type 默认 [type="baser64"] 其他参数 "blob", "buffer"
 * @returns {File|Blob|String}
 */
export const fileConvert = (
  file: File,
  type: string = "base64"
): Promise<string | Buffer | Blob> => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    if (type === "base64") {
      reader.readAsDataURL(file);
      reader.onload = () => {
        const dataurl = reader.result as string;
        resolve(dataurl);
      };
    } else if (type === "buffer") {
      reader.readAsArrayBuffer(file);
      reader.onload = () => {
        const arraybuffer = reader.result as ArrayBuffer;
        resolve(Buffer.from(arraybuffer));
      };
    } else if (type === "blob") {
      reader.readAsArrayBuffer(file);
      reader.onload = () => {
        const arraybuffer = reader.result as ArrayBuffer;
        resolve(new Blob([arraybuffer], { type: file.type }));
      };
    } else if (type === "URL") {
      resolve(URL.createObjectURL(file));
    }
  });
};

// 生成二维码
export const generateQR = async (
  dom: HTMLImageElement | string,
  text: string
) => {
  if (!text) {
    return "";
  }
  const imgElement =
    typeof dom === "string"
      ? (document.getElementById(dom) as HTMLImageElement)
      : dom;
  const src = await toDataURL(text);
  if (imgElement) {
    imgElement.src = src;
  }
  return src;
};

// 解析二维码
export const parseQR = (dom: HTMLImageElement | string) => {
  const imgElement =
    typeof dom === "string"
      ? (document.getElementById(dom) as HTMLImageElement)
      : dom;
  // 创建一个canvas元素来绘制图片
  const canvas: HTMLCanvasElement = document.createElement("canvas");
  const context: CanvasRenderingContext2D = canvas.getContext("2d")!;
  canvas.width = imgElement.naturalWidth;
  canvas.height = imgElement.naturalHeight;
  context.drawImage(imgElement, 0, 0);
  // 获取图片数据
  const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
  // 使用jsQR库转换二维码
  const code = jsQR(imageData.data, canvas.width, canvas.height);
  if (!code) {
    console.log("无法解析二维码");
  }
  return code?.data || "";
};

export const useFile = () => {
  return {
    downFile,
    fileConvert,
    generateQR,
    parseQR,
  };
};

export default useFile;
